package com.geek.novel.activity

import android.os.Bundle
import android.os.Message
import android.text.TextUtils
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import com.geek.novel.R
import com.geek.novel.activity.base.TitleBarActivity
import com.geek.novel.bo.AppContext
import com.geek.novel.common.Constant
import com.geek.novel.dialog.ConfirmDialog
import com.geek.novel.services.ImageService
import com.geek.novel.utils.*
import io.realm.Realm
import kotlinx.android.synthetic.main.activity_test_page.*
import java.io.File
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap

/**
 * 测试页面
 */
class TestPageActivity: TitleBarActivity() {

	override fun pageName(): String = AppContext.getContext().getString(R.string.title_bar_page_test_page)

	//图片的服务类
	private lateinit var imageService: ImageService

	/**确认框*/
	private lateinit var confirmDialog: ConfirmDialog

	override fun onCreate(savedInstanceState: Bundle?) {
		super.onCreate(savedInstanceState)
		setContentView(R.layout.activity_test_page)
		//图片服务
		imageService = ImageService(this)

		//确认框
		confirmDialog = ConfirmDialog(this)
	}

	/**附加控件*/
	override fun attachViewChild() {
        initSpinnerAdapter()
        setClickLsn()
	}

	override fun clickEvent(id: Int, v: View) {
		when(id){
			//上传数据库文件
			R.id.ly_upload_realm->{
				this.confirmUploadRealmFile()
			}
		}
	}


	var list = LinkedList<Map<String, String>>()
	private fun initSpinnerAdapter(){
		list = LinkedList<Map<String, String>>()
		addData("清除本地配置", "")
		addData("本地环境1", "http://192.168.8.148/")
		addData("本地环境2", "http://192.168.0.111/")
		addData("爬虫环境1", "http://110.40.242.114/")
		addData("正式环境", "http://106.55.154.216/")

		var spIndex = 0
		val dataList = ArrayList<String>()
		list.forEachIndexed {index,it->
			val key = it["key"]
			val value = it["value"]
			if(value == CurUrl){//设置默认选中
				spIndex = index
			}
			//处理显示的key
            var res = key
            if(value != ""){
                res = "$key: $value"
            }
            dataList.add("$res")
		}

		val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, dataList)
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)

		sp_httpServiceIp.adapter = adapter
		sp_httpServiceIp.setSelection(spIndex, true)//设置默认选中
	}

	private fun addData(key: String, value: String){
		val map = HashMap<String, String>()
		map["key"] = key
		map["value"] = value
		list.add(map)
	}

	private fun setClickLsn() {
		llayout_showDialog.setOnClickListener(this)

		ly_upload_realm.setOnClickListener(this)

		sp_httpServiceIp.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
			override fun onItemSelected(av: AdapterView<*>, v: View, position: Int, arg3: Long) {
				if(position >= list.size){
					ToastUtils.toast("IP设置出错")
					return
				}
				val item = list[position]
				val value = item["value"]
				CurUrl = value!!
				toggleHttpServiceIP()
			}

			override fun onNothingSelected(arg0: AdapterView<*>) {
			}
		}
	}


	fun toggleHttpServiceIP(){
		if(TextUtils.isEmpty(CurUrl)){
            SPUtil.remove(SPUtil.updateServiceIp, SPUtil.SP_UPDATE_HTTP_SERVICE_IP)
            ToastUtils.toast("默认地址已清除")
			return
		}
		//更新IP
		SPUtil.put(SPUtil.updateServiceIp, CurUrl, SPUtil.SP_UPDATE_HTTP_SERVICE_IP)
		ToastUtils.toast("地址已切换至: ${CurUrl},重启APP生效")
	}

	/**
	 * 上传本地的数据库realm文件
	 */
	private fun confirmUploadRealmFile(){
		val realm = Realm.getDefaultInstance()
		val file = File(realm.path)
		val size = file.length().toFloat() / 1000 /1000
		confirmDialog.openDialog("确认上传本地数据文件吗？数据库文件路径：${realm.path}, 大小：${size}M", "上传") {
			this.uploadRealmFile()
			confirmDialog.dismiss()
		}
	}

	/**
	 * 上传本地的数据库realm文件
	 */
	private fun uploadRealmFile(){
		val realm = Realm.getDefaultInstance()
		val file = File(realm.path)

		//获取当前用户的手机号或者用设备号
		val deviceId = CommUtil.deviceId

		//路径拼接上当前日期
		val date = DateUtil.getCurrentDate()
		val filePath = "$date/$deviceId"

		imageService.getFileService().uploadFile(file, "db", null, "android_db", filePath)
	}

	/**消息处理*/
	override fun handleMessage(msg: Message) {
		when(msg.what){
			//文件上传完毕
			Constant.handler_event_upload_file_finish->{
				ToastUtils.toast("文件上传完毕")
			}
		}
	}


	companion object {
		var CurUrl = Constant.HTTP_SERVICE_IP
	}

}